var GeolocateGmapsv3 = function( mapDiv, config ) {
	if ( config ) $.extend( this, config );
	if ( !mapDiv ) { 
		console.log( 'mapDiv must be specified.' ) 
	}
	if (typeof this.center == 'undefined') this.center = { lat: 39, lng: -108 };
	if (typeof this.zoom == 'undefined') this.zoom = 12;
	if (typeof this.showUncertaintyRadius == 'undefined') this.showUncertaintyRadius = true;
	if (typeof this.showUncertaintyPolygon == 'undefined') this.showUncertaintyPolygon = true;
	if (typeof this.popup == 'undefined') this.popup = false;
	
	this.data = null;
	this.locateUrl = 'http://www.museum.tulane.edu/webservices/geolocatesvcv2/glcwrap.aspx?';
	
	this.result = {};
	this.circle = [];
	this.polygon = [];
	
	this.infowindow = new google.maps.InfoWindow();
	this.map = new google.maps.Map(document.getElementById(mapDiv),{
		zoom: this.zoom,
		center: new google.maps.LatLng(this.center.lat, this.center.lng),
		mapTypeId: google.maps.MapTypeId.ROADMAP
	});

	var me = this;

	this.setCenter = function(lat,lng) {
		me.map.setCenter(new google.maps.LatLng(lat, lng));
	}

	this.onEachFeature = function(feature, type) {
		if(typeof type == 'undefined') type = '';
		google.maps.event.addListener(feature, "click", function(event) {
			switch(type) {
				case 'marker':
					me.onMarkerClick(event,feature);
					break;
				case 'circle':
					me.onCircleClick(event,feature);
					break;
				case 'polygon':
					me.onPolygonClick(event,feature);
					break;
				default:
					console.log('Wrong Type');
					break;
			}
		});
	}
	
	this.onMarkerClick = function(event,feature) {
		console.log('Marker Click');
		console.log(event);
		console.log(feature);

        var properties = [];
        for ( var p in feature.geojsonProperties ) properties.push( p + ': <strong>' + feature.geojsonProperties[p] + '</strong>' );
        $('#details').html( properties.join('<br>') );

		if ( me.popup ) {
			me.setInfoWindow(event,feature);
		}
	}

	this.onPolygonClick = function(event,feature) {
		console.log('Polygon Click');
		console.log(feature);
	}

	this.onCircleClick = function(event,feature) {
		console.log('Circle Click');
		console.log(feature);
	}

	
	this.setInfoWindow = function(event,feature) {
		var content = "<div id='infoBox'><strong>GeoJSON Feature Properties</strong><br />";
		for (var j in feature.geojsonProperties) {
			content += j + ": " + feature.geojsonProperties[j] + "<br />";
		}
		content += "</div>";
		me.infowindow.setContent(content);
		me.infowindow.position = event.latLng;
		me.infowindow.open(me.map);
	}

	this.enableUncertaintyRadius = function () {
		me.showUncertaintyRadius = true;
		if(!$.isEmptyObject(me.result)){me.loadResult(me.result)};
	}
	
	this.disableUncertaintyRadius = function () {
		me.showUncertaintyRadius = false;
		if(!$.isEmptyObject(me.result)){me.loadResult(me.result)};
	}

	this.enableUncertaintyPolygon = function () {
		me.showUncertaintyPolygon = true;
		if(!$.isEmptyObject(me.result)){me.loadResult(me.result)};
	}
	
	this.disableUncertaintyPolygon = function () {
		me.showUncertaintyPolygon = false;
		if(!$.isEmptyObject(me.result)){me.loadResult(me.result)};
	}
	
	this.loadResult = function(result) {
		me.clearMap();
		if(typeof result == 'object') {
			var opts = ('undefined' == me.style.markerOptions) ? {} : me.style.markerOptions;
			me.data = new GeoJSON(result,opts);
			if (me.data.length){
				var cle,ply;
				for (var i = 0; i < me.data.length; i++){
					if(i==0) {
                        var properties = [];
                        for ( var p in me.data[i].geojsonProperties ) properties.push( p + ': <strong>' + me.data[i].geojsonProperties[p] + '</strong>' );
                        $('#details').html( properties.join('<br>') );
						me.setCenter(me.data[i].position.lat(),me.data[i].position.lng());
					}
					if('undefined' != typeof me.data[i].geojsonProperties) {
						// Polygon
						if(me.showUncertaintyPolygon) {
						
							var poly = me.data[i].geojsonProperties.uncertaintyPolygon;
							if(typeof( poly ) == 'object') {
								opts = ('undefined' == me.style.polygonOptions) ? {} : me.style.polygonOptions;
								ply = new GeoJSON(poly,opts);
								ply.setMap(me.map);
								me.onEachFeature(ply, 'polygon');
								me.polygon.push(ply);
							}
						}
						// Circle
						if(me.showUncertaintyRadius) {
							if(me.data[i].geojsonProperties.uncertaintyRadiusMeters != 0 && me.data[i].geojsonProperties.uncertaintyRadiusMeters != '') {
								opts = ('undefined' == me.style.circleOptions) ? {} : me.style.circleOptions;
								opts['map'] = me.map;
								opts['radius'] = me.data[i].geojsonProperties.uncertaintyRadiusMeters;
								cle = new google.maps.Circle(opts);
								cle.bindTo('center', me.data[i], 'position');
								// cle['geojsonProperties'] = me.data[i].geojsonProperties;
								me.onEachFeature(cle, 'circle');
								me.circle.push(cle);
							}
						}
					}
					// Marker
					me.data[i].setMap(me.map);
					me.onEachFeature(me.data[i], 'marker');
					// if (me.data[i].geojsonProperties) {
						// me.setInfoWindow(me.data[i]);
					// }					
					
				}
			} else {
				me.setCenter(me.data.position.lat(),me.data.position.lng());
				me.data.setMap(me.map);
				if (me.data.geojsonProperties) {
					me.setInfoWindow(me.data);
				}
			}
		} else {
            $('#details').empty();
            console.log( 'No results' );
        }
	}
	
	this.clearMap = function(){
		if(me.polygon && me.polygon.length) {
			for(var j = 0; j < me.polygon.length; j++){
				me.polygon[j].setMap(null);
			}
			me.polygon = [];
		}
		if(me.circle && me.circle.length) {
			for(var j = 0; j < me.circle.length; j++){
				me.circle[j].setMap(null);
			}
			me.circle = [];
		}
		if (!me.data)
			return;
		if (me.data.length){
			for (var i = 0; i < me.data.length; i++){
				if(me.data[i].length){
					for(var j = 0; j < me.data[i].length; j++){
						me.data[i][j].setMap(null);
					}
				}
				else{
					me.data[i].setMap(null);
				}
			}
		}else{
			me.data.setMap(null);
		}
		if (me.infowindow.getMap()){
			me.infowindow.close();
		}
	}
	
	this.query = function(params){
		if('undefined' == typeof params['country'] ||'undefined' == typeof params['locality'] || params['country'] == '' || params['locality'] == '') {
			return false;
		}
		var querAr = [];
		for (var key in params) {
			if (params.hasOwnProperty(key)) {
				querAr.push(key + '=' + params[key]);
			}
		}
		// console.log(me.locateUrl+querAr.join('&'));
		querAr.push('fmt=geojson');
		$.ajax({
			url : me.locateUrl+querAr.join('&'),
			dataType: 'jsonp',
			timeout: 2000,
			callbackParameter: 'callback',
			success : function(result) {
				me.result = result;
				me.loadResult(result);
			},
			error: function(e,msg) {
				throw('Error retrieving Data: ' + msg);
			}
		});
	}

	
}
